package com.itheima.takeout.ui.adapter;

import android.content.Context;
import android.graphics.Paint;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.CycleInterpolator;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.itheima.takeout.MyApplication;
import com.itheima.takeout.R;
import com.itheima.takeout.model.net.bean.CacheSeletedInfo;
import com.itheima.takeout.model.net.bean.GoodsInfo;
import com.itheima.takeout.ui.activity.BusinessActivity;
import com.itheima.takeout.ui.fragment.GoodsFragment;
import com.itheima.takeout.util.Constant;
import com.squareup.picasso.Picasso;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;

/**
 * Created by Apple on 2016/9/3.
 */
public class GoodsAdapter extends BaseAdapter implements StickyListHeadersAdapter {

    private Context context;
    private List<GoodsInfo> goodsInfoList;
    private final MyApplication application;

    public void setGoodsInfoList(List<GoodsInfo> goodsInfoList) {
        this.goodsInfoList = goodsInfoList;
        notifyDataSetChanged();
    }

    private GoodsFragment goodsFragment;

    public GoodsAdapter(GoodsFragment goodsFragment,Context context, List<GoodsInfo> goodsInfoList) {
        this.goodsFragment = goodsFragment;
        this.context = context;
        this.goodsInfoList = goodsInfoList;
        application = (MyApplication) goodsFragment.getActivity().getApplication();
    }

    @Override
    public View getHeaderView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_type_header, parent, false);
        }
        TextView header = (TextView) convertView;
        header.setText(goodsInfoList.get(position).getTypeName());
        return convertView;
    }

    @Override
    public long getHeaderId(int position) {
        return goodsInfoList.get(position).getTypeId();
    }

    @Override
    public int getCount() {
        return goodsInfoList != null?goodsInfoList.size():0;
    }

    @Override
    public Object getItem(int i) {
        return goodsInfoList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if(view == null){
            view = LayoutInflater.from(context).inflate(R.layout.item_goods, viewGroup, false);
            holder = new ViewHolder(view);
            view.setTag(holder);
        }else{
            holder = (ViewHolder) view.getTag();
        }
        GoodsInfo goodsInfo = goodsInfoList.get(i);
        Picasso.with(context).load(goodsInfo.getIcon()).into(holder.ivIcon);
        holder.tvName.setText(goodsInfo.getName());
        if(TextUtils.isEmpty(goodsInfo.getForm())){
            holder.tvZucheng.setVisibility(View.GONE);
        }else{
            holder.tvZucheng.setVisibility(View.VISIBLE);
            holder.tvZucheng.setText(goodsInfo.getForm());
        }
        if(goodsInfo.getMonthSaleNum() == 0){
            holder.tvYueshaoshounum.setVisibility(View.GONE);
        }else{
            holder.tvYueshaoshounum.setVisibility(View.VISIBLE);
            holder.tvYueshaoshounum.setText("月销售"+goodsInfo.getMonthSaleNum()+"份");
        }
        holder.tvNewprice.setText("￥"+goodsInfo.getNewPrice());
        if(goodsInfo.getOldPrice() == 0){
            holder.tvOldprice.setVisibility(View.GONE);
        }else{
            holder.tvOldprice.setVisibility(View.VISIBLE);
            holder.tvOldprice.setText("￥"+goodsInfo.getOldPrice());
            holder.tvOldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        }
        if(goodsInfo.getCount() == 0){
            holder.ibMinus.setVisibility(View.GONE);
            holder.tvCount.setVisibility(View.GONE);
        }else{
            holder.ibMinus.setVisibility(View.VISIBLE);
            holder.tvCount.setVisibility(View.VISIBLE);
            holder.tvCount.setText(goodsInfo.getCount()+"");
        }
        holder.setPosition(i);
        return view;
    }

   class ViewHolder {
        @InjectView(R.id.iv_icon)
        ImageView ivIcon;
        @InjectView(R.id.tv_name)
        TextView tvName;
        @InjectView(R.id.tv_zucheng)
        TextView tvZucheng;
        @InjectView(R.id.tv_yueshaoshounum)
        TextView tvYueshaoshounum;
        @InjectView(R.id.tv_newprice)
        TextView tvNewprice;
        @InjectView(R.id.tv_oldprice)
        TextView tvOldprice;
        @InjectView(R.id.ib_minus)
        ImageButton ibMinus;
        @InjectView(R.id.tv_count)
        TextView tvCount;
        @InjectView(R.id.ib_add)
        ImageButton ibAdd;

        ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }


       @OnClick({R.id.ib_minus,R.id.ib_add})
       public void onClick(View view){
           int operator = Constant.ADD;
           switch (view.getId()){
               case R.id.ib_add:
                   doAddOperator(view);
                   break;
               case R.id.ib_minus:
                   doMinusOperator();
                   operator = Constant.MINUS;
                   break;
           }
           //获取商品类型的id
           int typeId = goodsInfoList.get(position).getTypeId();
            goodsFragment.goodsFragmentPresenter.updateSelectedTypeInfo(typeId,operator);

           //更新购物车  一定要获取购物车的数据
           ((BusinessActivity)context).businessActivityPresenter.updateCartData();

       }

       public void doMinusOperator(){
           GoodsInfo info = goodsInfoList.get(position);
           if(info.getCount() == 1){
                 //执行隐藏动画
               Animation hideAnimation = getHideAnimation();
               ibMinus.setAnimation(hideAnimation);
               tvCount.setAnimation(hideAnimation);
               ibMinus.setVisibility(View.GONE);
               tvCount.setVisibility(View.GONE);

               //删除缓存信息
               application.deleteCacheSelectedInfo(info.getId());
           }else{
               //更新缓存信息
               application.updateCacheSelectedInfo(info.getId(),info.getCount() - 1);
           }
           //修改数据
           info.setCount(info.getCount() - 1);
           //修改显示
           tvCount.setText(info.getCount()+"");
       }


       private void doAddOperator(View view) {
           GoodsInfo info = goodsInfoList.get(position);
                if(info.getCount() == 0){
                    Animation showAnimation = getShowAnimation();
                    ibMinus.setAnimation(showAnimation);
                    tvCount.setAnimation(showAnimation);
                    ibMinus.setVisibility(View.VISIBLE);
                    tvCount.setVisibility(View.VISIBLE);
                    //添加缓存信息
                    application.addCacheSelectedInfo(new CacheSeletedInfo(info.getSellerId(),info.getTypeId(),info.getId(),1));
                }else{
                    //更新缓存信息
                    application.updateCacheSelectedInfo(info.getId(),info.getCount()+1);
                }

           //修改数据
           info.setCount(info.getCount()+1);
           //修改显示
           tvCount.setText(info.getCount()+"");
           //要执行从点击+号的位置，有一个+号从点击的位置移动到购物车
           /*
           1 在整个界面上添加一个+号
           2 让新创建的+号执行动画
           3  动画执行完成移除添加的+号
           * */
           ImageButton ib = new ImageButton(context);
           int[] srcLocation = new int[2];
           view.getLocationInWindow(srcLocation);
           ib.setX(srcLocation[0]);
           ib.setY(srcLocation[1]);
           ib.setBackgroundResource(R.drawable.button_add);
           ((BusinessActivity)context).addImageButton(ib,view.getWidth(),view.getHeight());

           int[] destLocation = ((BusinessActivity) context).getImageCartLocation();

           playAnimation(ib,srcLocation,destLocation);

       }

       /**
        * 执行动画
        * @param ib
        * @param srcLocation
        * @param destLocation
        */
       private void playAnimation(final ImageButton ib, int[] srcLocation, int[] destLocation) {
            Animation animation = createAnimation(srcLocation,destLocation);
            ib.startAnimation(animation);
           animation.setAnimationListener(new Animation.AnimationListener() {
               @Override
               public void onAnimationStart(Animation animation) {

               }

               @Override
               public void onAnimationEnd(Animation animation) {
                   //移除+号
                   ((BusinessActivity) context).removeImageButton(ib);
               }

               @Override
               public void onAnimationRepeat(Animation animation) {

               }
           });
       }

       /**
        * 创建移动的动画
        * @param srcLocation
        * @param destLocation
        * @return
        */
       private Animation createAnimation(int[] srcLocation, int[] destLocation) {
           AnimationSet set = new AnimationSet(false);
           //x轴的平移动画
           TranslateAnimation translateX = new TranslateAnimation(TranslateAnimation.ABSOLUTE,0,TranslateAnimation.ABSOLUTE,destLocation[0] - srcLocation[0],
                   TranslateAnimation.ABSOLUTE,0,TranslateAnimation.ABSOLUTE,0
                   );
           translateX.setInterpolator(new LinearInterpolator());
           set.addAnimation(translateX);
           TranslateAnimation translateY = new TranslateAnimation(TranslateAnimation.ABSOLUTE,0,TranslateAnimation.ABSOLUTE,0,
                   TranslateAnimation.ABSOLUTE,0,TranslateAnimation.ABSOLUTE,destLocation[1] - srcLocation[1]
           );
           translateY.setInterpolator(new AccelerateInterpolator());
           set.addAnimation(translateY);
           set.setDuration(500);
           return set;
       }


       int position;
       public void setPosition(int i) {
           this.position = i;
       }
   }

    /**
     * 创建显示动画
     * @return
     */
    private Animation getShowAnimation(){
        AnimationSet set = new AnimationSet(true);
        //旋转
        RotateAnimation rotate = new RotateAnimation(0,720,RotateAnimation.RELATIVE_TO_SELF,0.5f,RotateAnimation.RELATIVE_TO_SELF,0.5f);
        set.addAnimation(rotate);
        //平移
        TranslateAnimation translate = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_SELF,2,TranslateAnimation.RELATIVE_TO_SELF,0,TranslateAnimation.RELATIVE_TO_SELF,0,TranslateAnimation.RELATIVE_TO_SELF,0);
        set.addAnimation(translate);
        //透明度改变
        AlphaAnimation alpha = new AlphaAnimation(0,1);
        set.addAnimation(alpha);
        set.setDuration(500);
        return set;
    }

    /**
     * 创建显示动画
     * @return
     */
    private Animation getHideAnimation(){
        AnimationSet set = new AnimationSet(true);
        //旋转
        RotateAnimation rotate = new RotateAnimation(0,720,RotateAnimation.RELATIVE_TO_SELF,0.5f,RotateAnimation.RELATIVE_TO_SELF,0.5f);
        set.addAnimation(rotate);
        //平移
        TranslateAnimation translate = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_SELF,0,TranslateAnimation.RELATIVE_TO_SELF,1,TranslateAnimation.RELATIVE_TO_SELF,0,TranslateAnimation.RELATIVE_TO_SELF,0);
        set.addAnimation(translate);
        //透明度改变
        AlphaAnimation alpha = new AlphaAnimation(1,0);
        set.addAnimation(alpha);
        set.setDuration(500);
        return set;
    }

}
